package com.suchbear.homeiot

import android.util.Log
import java.io.IOException
import java.net.*

class UDPClient(private val receiveMessageListener: ReceiveMessageListener) : Runnable {
    private val udpPort: Int = 10211
    private val hostIP: String = "1.117.3.120"
    private lateinit var socket: DatagramSocket
    private lateinit var packetSend: DatagramPacket
    private lateinit var packetRcv: DatagramPacket
    private var udpLife: Boolean = true
    private var msgRcv: ByteArray = ByteArray(1024)

    fun isUdpLife(): Boolean {
        return udpLife
    }

    fun setUdpLife(b: Boolean) {
        udpLife = b
    }

    fun send(msgSend: String) {
        var hostAddress: InetAddress? = null
        try {
            hostAddress = InetAddress.getByName(hostIP)
        } catch (e: UnknownHostException) {
            e.printStackTrace()
        }

        packetSend =
            DatagramPacket(msgSend.toByteArray(), msgSend.toByteArray().size, hostAddress, udpPort)
        try {
            if (::socket.isInitialized) {
                socket.send(packetSend)
            } else {
                Log.i("udpClient", "发送失败,连接未建立")
            }
        } catch (e: IOException) {
            e.printStackTrace()
            Log.i("udpClient", "发送失败")
        }
    }

    override fun run() {
        try {
            socket = DatagramSocket()
            socket.soTimeout = 3000
        } catch (e: SocketException) {
            Log.i("udpClient", "建立接收数据报失败")
            e.printStackTrace()
        }
        packetRcv = DatagramPacket(msgRcv, msgRcv.size)
        while (udpLife) {
            try {
                Log.i("udpClient", "UDP监听")
                socket.receive(packetRcv)
                val rcvMsg = String(packetRcv.data, packetRcv.offset, packetRcv.length)
                receiveMessageListener.onMessage(rcvMsg)

                Log.i("Rcv", rcvMsg)
            } catch (e: IOException) {
                e.printStackTrace()
            }
        }

        Log.i("udpClient", "udp监听关闭")
        socket.close()
    }
}